/*
 * Copyright (C) 2010- Peer internet solutions
 *
 * This file is part of mixare.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>
 */

#import "AugmentedGeoViewController.h"
#import "PoiItem.h"
#import "PopupView.h"
#import "LoadingView.h"

@interface AugmentedGeoViewController ()

@property (nonatomic, retain) MarkerView *lastestSelectedMarkerView;
@property (nonatomic, retain) PoiItem *currentSelectedPOIItem;

@end

@implementation AugmentedGeoViewController

@synthesize centerLocation;

- (id)init {
    self = [super init];
    [self viewWillAppear:YES];
	self.scaleViewsBasedOnDistance = YES;
	self.rotateViewsBasedOnPerspective = YES;
    _isLoadingEnquireBranchesData = NO;
    
//    _dataConnection = [[HTTPConnectionUtility alloc] init];
//
//    
//    _dataConnection.connectionDelegate = self;
//    _dataConnection.tagId= nil;
    
    _positionsArray = [[NSMutableArray alloc] init];
    _resultArray = [[NSMutableArray alloc] init];
    
//    self.abslModule = [[[ControllerManager getRootViewController].rootViewControllerWithPublicHome
//                        getModuleWthKeyInModules:@"absl"]objectAtIndex:0];
    
//    [self initNavigationBar];
    [self showLoadingView];
    
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenPopupView)];
    [self.view addGestureRecognizer:recognizer];

    return self;
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
}

- (BOOL)prefersStatusBarHidden
{
    return NO;
}

- (void)initNavigationBar {
    
    _navBar = [[UIView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, 44)];
    _navBar.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_navBar];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
    imageView.image = [UIImage imageNamed:@"ph_header.png"];
    [_navBar addSubview:imageView];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(5, 8, 60, 28);
    [backBtn setBackgroundImage:[UIImage imageNamed:@"ph_back-button.png"] forState:UIControlStateNormal];
    backBtn.titleLabel.textColor = [UIColor whiteColor];
    backBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [backBtn setTitle:@"Back" forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [_navBar addSubview:backBtn];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 120, 44)];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont boldSystemFontOfSize:16];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.text = @"ATM/Branch";
    [_navBar addSubview:titleLabel];
    
    UIButton *mapBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    mapBtn.frame = CGRectMake(255, 8, 60, 28);
    [mapBtn setBackgroundImage:[UIImage imageNamed:@"ph_Filter.png"] forState:UIControlStateNormal];
    mapBtn.titleLabel.textColor = [UIColor whiteColor];
    mapBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [mapBtn setTitle:@"Map" forState:UIControlStateNormal];
    [mapBtn addTarget:self action:@selector(showMap) forControlEvents:UIControlEventTouchUpInside];
    [_navBar addSubview:mapBtn];
    
}

- (void)backAction {
//    if (_updateTimer.isValid) {
//        [_updateTimer invalidate];
//    }
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)showMap {
//    NSString *publicHomeABSLNibName = [DeviceUtil getNibNameWithCurrentDevice:@"PublicHomeABSLView"];
//
//    PublicHomeABSLViewController *publicHomeABSLController = [[PublicHomeABSLViewController alloc] initWithNibName:publicHomeABSLNibName bundle:nil];
//
//    if (_filterModule != nil)
//    {
//        publicHomeABSLController.filterModule = [NSDictionary dictionaryWithDictionary:_filterModule];
//    }
//
//    [self.navigationController pushViewController:publicHomeABSLController animated:YES];

}

// UI loading view
-(void) showLoadingView
{
    if (loadingView == nil) {
        loadingView = [[LoadingView alloc] initWithFrame:self.view.frame];
    }
    [self.view addSubview:loadingView];
    loadingView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    [loadingView showLoading:nil];
    [self.view bringSubviewToFront:loadingView];
    //Function #15.Improve log on journey End: by Emmy Xiao on 06/25/2014
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

-(void) removeLoadingView
{
    if (loadingView != nil)
    {
        [loadingView hideLoading];
        [loadingView removeFromSuperview];
        loadingView = nil;
    }
    //Function #15.Improve log on journey End: by Emmy Xiao on 06/25/2014
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}



- (void)showDetailView:(PoiItem *)poiItem {
//    NSDictionary *item = [_resultArray objectAtIndex:poiItem.position.index];
//    
//    NSString *detailsViewNibName = [DeviceUtil getNibNameWithCurrentDevice:@"PublicHomeABSLDetailsView"];
//    
//    PublicHomeABSLDetailsViewController *detailsView = [[PublicHomeABSLDetailsViewController alloc] initWithNibName:detailsViewNibName
//                                                                                                             bundle:nil];
//    
//    NSDictionary *pageItems     = [[self.abslModule objectForKey:@"pageItems"]objectAtIndex:0];
//    NSDictionary *detailsConfig = [[pageItems objectForKey:@"detail"]objectAtIndex:0];
//    
//    detailsView.detailsModule = [NSDictionary dictionaryWithDictionary:item];
//    detailsView.detailsConfig = [NSDictionary dictionaryWithDictionary:detailsConfig];
//    
//    [self.navigationController pushViewController:detailsView animated:YES];
}

- (void)setCenterLocation:(CLLocation*)newLocation {
	centerLocation = newLocation;
	for (PoiItem *geoLocation in self.coordinates) {
        [geoLocation calibrateUsingOrigin:centerLocation];
		if (geoLocation.radialDistance > self.maximumScaleDistance) {
			self.maximumScaleDistance = geoLocation.radialDistance;
		}
	}
}

- (void)showPopupViewWithPOIItem:(PoiItem *)poiItem {
    if (!_popUpView) {
        _popUpView = [[PopupView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, self.view.bounds.size.height)];
        _popUpView.delegate = self;
    }
    [self.view addSubview:_popUpView];
    _popUpView.poiItem = poiItem;
    if (_popUpView.frame.origin.y == self.view.frame.size.height) {
        [UIView beginAnimations:@"" context:nil];
        [UIView setAnimationDuration:0.3];
        _popUpView.frame = CGRectMake(0, self.view.bounds.size.height-150, self.view.bounds.size.width, self.view.bounds.size.height);
        [UIView commitAnimations];
    }
   // double distance = [_startPoint distanceFromLocation:self.currentSelectedPOIItem.geoLocation];
   // _popUpView.distance = distance;
}

- (void)hiddenPopupView {

    [UIView beginAnimations:@"" context:nil];
    [UIView setAnimationDuration:0.3];
    _popUpView.frame = CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, self.view.bounds.size.height);
    [UIView commitAnimations];
    [self dismissPopupView];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	return NO;
}

- (void)locationManager:(CLLocationManager*)manager didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation {
    
    [super locationManager:manager didUpdateToLocation:newLocation fromLocation:oldLocation];
    
    
    BOOL shouldRefreshPOI = NO;
    
    if (_startPoint == nil) {
        
        shouldRefreshPOI = YES;
        
    } else {
//        if ([_startPoint distanceFromLocation:newLocation] > 100000) {
//            shouldRefreshPOI = YES;
//        }
    }
    _startPoint = newLocation;
    if (shouldRefreshPOI) {
        
        [self startFetchPOIs];
    }
    
    
//    double distance = [_startPoint distanceFromLocation:self.currentSelectedPOIItem.geoLocation];
//    _popUpView.distance = distance;
    
//    for (MarkerView *markerView in ar_coordinateViews) {
//        double distance = [_startPoint distanceFromLocation:markerView.poiItem.geoLocation];
//        NSString *labelText = [NSString stringWithFormat:@"%.2fM", distance];
//        markerView.distanceLable.text = labelText;
//    }
}

- (void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error {
    
    [self removeLoadingView];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"Can not get current location, please retry later" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    [alertView show];
}

- (void)startFetchPOIs {
    [self loadEnquireBranchesData];
}

- (void) loadEnquireBranchesData {
    [self refreshPage];
/*comment for demo
    //    NSString *currentLanuage = [Language getLanguage];
    //test
//        CLLocation *testLocation = [[CLLocation alloc] initWithLatitude:22.3095009405 longitude:114.1799169764];
//        _startPoint = testLocation;
    // get prepare data for filter
    NSDictionary *searchData = [[self.abslModule objectForKey:@"searchData"]objectAtIndex:0];
    
    NSDictionary *defaultValues = [[searchData objectForKey:@"defaultValues"]objectAtIndex:0];
    //NSString *dataurl= [[[searchData objectForKey:@"dataurl"]objectAtIndex:0]objectForKey:currentLanuage];
    
    // prepare request params start
    NSMutableDictionary *requestParams = [[NSMutableDictionary alloc]init];
    
    // setup map request params.
    float longitudeDelta = 0.03;
    float latitudeDelta = 0.03;
    if ([self.abslModule objectForKey:@"radius"]) {
        longitudeDelta = 0.01*[[self.abslModule objectForKey:@"radius"] floatValue];
        latitudeDelta = 0.01*[[self.abslModule objectForKey:@"radius"] floatValue];
    }
    CLLocationDegrees leftDegrees   = _startPoint.coordinate.longitude - (longitudeDelta / 2.0);
    CLLocationDegrees rightDegrees  = _startPoint.coordinate.longitude + (longitudeDelta / 2.0);
    CLLocationDegrees bottomDegrees = _startPoint.coordinate.latitude  - (latitudeDelta  / 2.0);
    CLLocationDegrees topDegrees    = _startPoint.coordinate.latitude  + (latitudeDelta  / 2.0);
    
    NSString *bottomLeftLat = [[NSNumber numberWithDouble:bottomDegrees]stringValue];
    NSString *bottomLeftLng = [[NSNumber numberWithDouble:leftDegrees]stringValue];
    NSString *topRightLat   = [[NSNumber numberWithDouble:topDegrees]stringValue];
    NSString *topRightLng   = [[NSNumber numberWithDouble:rightDegrees]stringValue];
    
    [requestParams setObject:bottomLeftLat forKey:@"bottomLeftLat"];
    [requestParams setObject:bottomLeftLng forKey:@"bottomLeftLng"];
    [requestParams setObject:topRightLat   forKey:@"topRightLat"];
    [requestParams setObject:topRightLng   forKey:@"topRightLng"];
    
    // Comment start
    // For not to use the map center location, but to use focus location.
    // CLLocationDegrees centerLat = self.mapLocationsView.region.center.latitude;
    // CLLocationDegrees centerLng = self.mapLocationsView.region.center.longitude;
    //
    // NSString *cLat = [[NSNumber numberWithDouble:centerLat]stringValue];
    // NSString *cLng = [[NSNumber numberWithDouble:centerLng]stringValue];
    // Comment end
    
    [requestParams setObject:[[NSNumber numberWithDouble:_startPoint.coordinate.latitude] stringValue]  forKey:@"cLat"];
    [requestParams setObject:[[NSNumber numberWithDouble:_startPoint.coordinate.longitude] stringValue]  forKey:@"cLng"];
    
    // setup filters
    NSArray *selectedLocationTyps = [NSArray arrayWithObjects:@"show-all-results", nil];
    if ((selectedLocationTyps !=nil)&&([selectedLocationTyps count]>0))
    {
        NSArray *selectedLocations = [NSArray arrayWithArray:selectedLocationTyps];
        [requestParams setObject:selectedLocations forKey:@"location_type"];
    }
    
    // setup event
    if ([defaultValues objectForKey:@"event"]!=nil)
    {
        [requestParams setObject:[defaultValues objectForKey:@"event"] forKey:@"event"];
    }
    
    // setup country
    if ([defaultValues objectForKey:@"country"]!=nil)
    {
        [requestParams setObject:[defaultValues objectForKey:@"country"] forKey:@"country"];
    }
    
    // setup json
    [requestParams setObject:@"" forKey:@"json"];
    
    // setup ver
    [requestParams setObject:@"" forKey:@"ver"];
    
    // setup address
    [requestParams setObject:@"" forKey:@"address"];
    
    NSString *dataurl = [NSString stringWithFormat:@"https://www.apps.asiapacific.hsbc.com/1/2/services/ABSL?event=go_cmd_absl_enquire&country=CN&location_type=branch&address=&cLat=%@&cLng=%@&bottomLeftLat=%@&bottomLeftLng=%@&topRightLat=%@&topRightLng=%@&LOCALE=en&rand=0.27969392971135676",[[NSNumber numberWithDouble:_startPoint.coordinate.latitude] stringValue],[[NSNumber numberWithDouble:_startPoint.coordinate.longitude] stringValue],bottomLeftLat,bottomLeftLng,topRightLat,topRightLng];
    
    if ([[defaultValues objectForKey:@"country"] isEqualToString:@"HK"]) {
        dataurl = @"https://hbappws:Asdf1234@www.qualityassurance61.hsbc.com.hk/1/PA_Mobile15ABSL4/ABSLFCServlet?LOCALE=en";
    }
    
    // prepare request params end
//    NSString *dataurl = [NSString stringWithFormat:@"https://www.apps.asiapacific.hsbc.com/1/2/services/ABSL?event=go_cmd_absl_enquire&country=CN&location_type=branch&address=&cLat=%@&cLng=%@&bottomLeftLat=%@&bottomLeftLng=%@&topRightLat=%@&topRightLng=%@&LOCALE=en&rand=0.27969392971135676",[[NSNumber numberWithDouble:_startPoint.coordinate.latitude] stringValue],[[NSNumber numberWithDouble:_startPoint.coordinate.longitude] stringValue],bottomLeftLat,bottomLeftLng,topRightLat,topRightLng];
    
    
    
    BOOL connectFlag = [_dataConnection createHTTPFormProxyConnectionWithDictionary:dataurl
                                                                        requestDict:nil
                                                                      requestMethod:@"GET"
                                                                            timeout:http_con_default_timeout
                                                                     needHSBCHeader:YES];
    
    if (connectFlag == NO)
    {
        // can not get connect call fail to handle
        [self networkErrorAlert];
        return;
    }
    
    _isLoadingEnquireBranchesData = YES;
    
    [self showLoadingView];
 */
}


- (void)networkErrorAlert {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Network Error, Please Try Again Later" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alertView show];

}

- (void)initControls {
    [self initInterface];
//    if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) {
//        [self setViewToLandscape];
//    }
}


- (void)initInterface {
    [super initInterface];
    [self.view bringSubviewToFront:_navBar];
}
#pragma mark -
#pragma mark - HTTPConnectionDelegate
//-(void) receiveResponse:(NSData *)receiveData connectId:(NSString *)connectId
//{
//    // reset the loading flag.
//    _isLoadingEnquireBranchesData = NO;
//    
//    [self removeLoadingView];
//    [_resultArray removeAllObjects];
//    [_positionsArray removeAllObjects];
//    
//    DebugLog(@"receiveResponse connectId %@",connectId);
//    
//    NSString *returnString = [[NSString alloc] initWithData:receiveData encoding:NSUTF8StringEncoding];
//    
//    DebugLog(@"returnString is %@",returnString);
//    
//    NSDictionary *dataInfo= [returnString JSONValue];
//    
//    if ([[dataInfo objectForKey:@"body"] objectForKey:@"results"] && [[[dataInfo objectForKey:@"body"] objectForKey:@"results"] isKindOfClass:[NSArray class]]) {
//        for (int i = 0 ; i < [[[dataInfo objectForKey:@"body"] objectForKey:@"results"] count];  i++) {
//            if (![[[[[dataInfo objectForKey:@"body"] objectForKey:@"results"] objectAtIndex:i] objectForKey:@"locationId"] isEqualToString:@"CNQ_GUH"]) {
//                [_positionsArray addObject:[Position parserHSBCBranchInfoToPosition:[[[dataInfo objectForKey:@"body"] objectForKey:@"results"] objectAtIndex:i] index:i]];
//            }
//        }
//        _resultArray = [[dataInfo objectForKey:@"body"] objectForKey:@"results"];
//    }
////    if ([[dataInfo objectForKey:@"body"] objectForKey:@"results"] && [[[dataInfo objectForKey:@"body"] objectForKey:@"results"] isKindOfClass:[NSArray class]]) {
////        for (int i = 0 ; i < 2;  i++) {
////            if (![[[[[dataInfo objectForKey:@"body"] objectForKey:@"results"] objectAtIndex:0] objectForKey:@"locationId"] isEqualToString:@"CNQ_GUH"]) {
////                [_positionsArray addObject:[Position parserHSBCBranchInfoToPosition:[[[dataInfo objectForKey:@"body"] objectForKey:@"results"] objectAtIndex:0] index:i]];
////            }
////        }
////        _resultArray = [[dataInfo objectForKey:@"body"] objectForKey:@"results"];
////    }
//    
//    
//    [self refreshWithHSBCBranchInfoPIO:_positionsArray];
//    self.centerLocation = _startPoint;
//    [self initControls];
//}
//
//-(void) getFailResponse:(NSString *)errorCode connectId:(NSString *)connectId
//{
//    // reset loading flag
//    _isLoadingEnquireBranchesData = NO;
//    
//    [self removeLoadingView];
//    [self networkErrorAlert];
//    
//}

- (void)refreshPage {
    [self removeLoadingView];
    NSArray *pois = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ABSLDemo.plist" ofType:nil]];
    
    for (int i = 0 ; i < [pois count];  i++) {
       [_positionsArray addObject:[Position parserHSBCBranchInfoToPositionForDemo:[pois objectAtIndex:i] index:i]];
    }
    [self refreshWithHSBCBranchInfoPIO:_positionsArray];
    self.centerLocation = _startPoint;
    [self initControls];
}

- (void)touchedPOIItem:(PoiItem *)branchInfo markerView:(MarkerView *)markerView{
    self.currentSelectedPOIItem = branchInfo;
    [_lastestSelectedMarkerView setIsHighLight:NO];
    [markerView setIsHighLight:YES];
    _lastestSelectedMarkerView = markerView;
    [self showPopupViewWithPOIItem:branchInfo];
}

- (void)touchPopupView:(PoiItem *)poiItem {
    self.currentSelectedPOIItem = poiItem;
    [self showDetailView:poiItem];

}

- (void)dismissPopupView {
    [_lastestSelectedMarkerView setIsHighLight:NO];
}

@end
